<template>
  <div class="flex h-screen bg-slate-50" style="min-width: 0; overflow: hidden;">
    <!-- 左侧边栏 -->
    <Sidebar
      :sidebar-open="sidebarOpen"
      :selected-robot="selectedRobot"
      :search-query="searchQuery"
      :selected-conversation="selectedConversation"
      :conversations="conversations"
      :filtered-conversations="filteredConversations"
      @toggle-sidebar="sidebarOpen = !sidebarOpen"
      @new-conversation="createNewConversation"
      @select-conversation="selectConversation"
      @update:selected-robot="selectedRobot = $event"
      @update:search-query="searchQuery = $event"
      @logout="handleLogout"
    />

    <!-- 右侧主内容区 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航栏 -->
      <nav class="bg-white shadow-sm border-b border-slate-200 px-6 py-4">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-4">
            <h2 class="text-xl font-semibold text-slate-800">
              {{ selectedConversation?.title || '智能助手' }}
            </h2>
            <div v-if="selectedConversation" class="flex items-center space-x-2">
              <span class="px-2 py-1 bg-indigo-100 text-indigo-700 text-xs rounded-full">
                {{ getConversationTypeLabel(selectedConversation.type) }}
              </span>
              <span class="text-xs text-slate-500">
                {{ formatDate(selectedConversation.created_at) }}
              </span>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <div class="flex items-center space-x-2">
              <img :src="authStore.user?.avatar || '/default-avatar.png'" 
                   alt="User Avatar" 
                   class="w-8 h-8 rounded-full">
              <div>
                <p class="text-sm font-medium text-slate-800">{{ authStore.user?.username || '用户' }}</p>
                <p class="text-xs text-slate-500">{{ authStore.user?.email || 'user@example.com' }}</p>
              </div>
            </div>
          </div>
        </div>
      </nav>

      <!-- 主内容区域 -->
      <div class="flex-1 overflow-hidden">
        <!-- 聊天区域 -->
        <div class="h-full flex">
          <!-- 消息列表 -->
          <div class="flex-1 overflow-y-auto p-6">
            <div class="max-w-4xl mx-auto space-y-6">
              <!-- 消息内容 -->
              <div v-for="message in messages" :key="message.id" 
                   class="flex" 
                   :class="{ 'justify-end': message.role === 'user' }">
                <div class="flex max-w-3xl" :class="{ 'flex-row-reverse': message.role === 'user' }">
                  <div class="flex-shrink-0">
                    <div class="w-8 h-8 rounded-full flex items-center justify-center"
                         :class="message.role === 'user' ? 'bg-indigo-500' : 'bg-purple-500'">
                      <i :class="message.role === 'user' ? 'fas fa-user' : 'fas fa-robot'" 
                         class="text-white text-sm"></i>
                    </div>
                  </div>
                  <div class="mx-3 flex-1">
                    <div class="p-4 rounded-lg" 
                         :class="message.role === 'user' 
                           ? 'bg-indigo-500 text-white' 
                           : 'bg-white border border-slate-200 text-slate-800'">
                      <p class="whitespace-pre-wrap">{{ message.content }}</p>
                    </div>
                    <p class="text-xs text-slate-500 mt-1" 
                       :class="{ 'text-right': message.role === 'user' }">
                      {{ formatTime(message.created_at) }}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧处理任务面板 -->
          <div v-if="selectedConversation && processingTasks.length > 0" 
               class="w-80 bg-white border-l border-slate-200 p-4">
            <h3 class="font-semibold text-slate-800 mb-4">处理进度</h3>
            <div class="space-y-3">
              <div v-for="task in processingTasks" :key="task.id" 
                   class="border border-slate-200 rounded-lg p-3">
                <div class="flex items-center justify-between mb-2">
                  <div class="flex items-center space-x-2">
                    <i :class="task.icon" class="text-slate-600"></i>
                    <span class="text-sm font-medium text-slate-800">{{ task.title }}</span>
                  </div>
                  <div class="w-2 h-2 rounded-full" 
                       :class="getTaskStatusColor(task.status)"></div>
                </div>
                <p class="text-xs text-slate-600">{{ task.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="border-t border-slate-200 bg-white p-4">
        <div class="max-w-4xl mx-auto">
          <div class="flex items-end space-x-4">
            <div class="flex-1">
              <textarea
                v-model="newMessage"
                placeholder="输入您的问题..."
                class="w-full p-3 border border-slate-300 rounded-lg resize-none focus:outline-none focus:border-indigo-500"
                rows="3"
                @keydown.ctrl.enter="handleSendMessage"
              ></textarea>
            </div>
            <div class="flex flex-col space-y-2">
              <button @click="handleSendMessage" 
                      :disabled="!newMessage.trim() || isLoading"
                      class="px-4 py-2 bg-indigo-500 text-white rounded-lg hover:bg-indigo-600 disabled:opacity-50 disabled:cursor-not-allowed">
                <i class="fas fa-paper-plane"></i>
              </button>
              <button @click="toggleVoiceRecognition" 
                      class="px-4 py-2 border border-slate-300 rounded-lg hover:bg-slate-50">
                <i class="fas fa-microphone"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useHomeState } from '../composables/home/useHomeState'
import { useVoiceRecognition } from '../composables/home/useVoiceRecognition'
import Sidebar from '../components/home/Sidebar.vue'
import { getConversationIcon, formatDate, formatTime, getConversationTypeLabel } from '../utils/home'

const router = useRouter()
const authStore = useAuthStore()

// 使用状态管理
const {
  sidebarOpen,
  selectedRobot,
  searchQuery,
  selectedConversation,
  newMessage,
  isLoading,
  messages,
  conversations,
  processingTasks,
  filteredConversations,
  createNewConversation,
  selectConversation,
  sendMessage
} = useHomeState()

// 语音识别
const { isRecording, startRecording, stopRecording } = useVoiceRecognition()

// 发送消息
const handleSendMessage = async () => {
  if (!newMessage.value.trim() || isLoading.value) return
  
  try {
    await sendMessage(newMessage.value)
    newMessage.value = ''
  } catch (error) {
    console.error('Failed to send message:', error)
  }
}

// 切换语音识别
const toggleVoiceRecognition = () => {
  if (isRecording.value) {
    stopRecording()
  } else {
    startRecording((text) => {
      newMessage.value = text
    })
  }
}

// 获取任务状态颜色
const getTaskStatusColor = (status: string) => {
  switch (status) {
    case 'completed':
      return 'bg-green-500'
    case 'processing':
      return 'bg-yellow-500'
    default:
      return 'bg-gray-300'
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await authStore.logout()
    router.push('/login')
  } catch (error) {
    console.error('Failed to logout:', error)
  }
}
</script>

<style scoped>
/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>